'use strict';
const dayjs = require('dayjs');
const { desensitization } = require('../utils');

const Service = require('egg').Service;

class ExpertEvaluationService extends Service {

  async countByQuery({ orderId }) {
    const query = { order_id: orderId };
    const count = await this.ctx.model.ExpertEvaluate.count(query);
    return count
  }

  async getEvaluationListByQuery({ expertId, pageNum = 1, pageSize = 6 }) {
    const query = { expert_id: expertId, deleted: false };
    const options = {
      skip: (pageNum - 1) * pageSize,
      limit: pageSize,
      sort: '-create_at'
    };

    const evaluates = await this.ctx.model.ExpertEvaluate.find(query, [
      '_id', 'content', 'create_at', 'user_id'
    ], options).lean();

    const totalCount = await this.ctx.model.ExpertEvaluate.count(query);

    let evaluateList = evaluates.map((item) => {
      return {
        _id: item._id.toString(),
        content: item.content,
        user_id: item.user_id,
        create_at: dayjs(item.create_at).format('YYYY-MM-DD HH:mm:ss'),
      };
    });

    evaluateList = await Promise.all(
      evaluateList.map(async (item) => {
        const user = await this.ctx.model.User.findOne({
          _id: item.user_id,
        },
        ['name', 'user_info']
        ).lean();
        console.log('')
        if (user && user.user_info && user.user_info.nickName) {
          item.user = {
            name: desensitization(user.user_info.nickName, 1, -1) 
          }
        }
        if (user && user.name) {
          
          item.user = {
            name: desensitization(user.name, 1, -1) 
          }
        }
        return item;
      })
    )


    if (!evaluateList) { return []; }

    return [ evaluateList, totalCount ];
  }

  async newAndSave(obj) {
    const evaluate = new this.ctx.model.ExpertEvaluate();
    
    evaluate.order_id = obj.order_id;
    evaluate.expert_id = obj.expert_id;
    evaluate.user_id = obj.user_id;
    evaluate.score = obj.score;
    evaluate.content = obj.content;
    evaluate.tags = obj.tags;
    
    
    const expertQuery = { _id: obj.expert_id };
    const e = await this.ctx.model.Expert.findOne(expertQuery).lean();
    
    if (e && e.evaluate_total_count) {
      await this.ctx.model.Expert.update(expertQuery, { $inc: { evaluate_total_count: 1 } });
    } else if (e)  {
      await this.ctx.model.Expert.update(expertQuery, { evaluate_total_count: 1 });
    }

    return evaluate.save();
  }
}

module.exports = ExpertEvaluationService;
